package authentication

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"errors"
)

var key = []byte("Za!1B2@c3#)*Gx7A")

//
// PKCS7Padding
// @Description:
// @param ciphertext
// @param blockSize
// @return []byte
//
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	paddingContent := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, paddingContent...)
}

//
// PKCS7UnPadding
// @Description:
// @param origin
// @return []byte
// @return error
//
func PKCS7UnPadding(origin []byte) ([]byte, error) {
	length := len(origin)
	if length == 0 {
		return nil, errors.New("remove padding failed")
	} else {
		unPadding := int(origin[length-1])
		return origin[:(length - unPadding)], nil
	}
}

//
// aesEncrypt
// @Description:
// @param origData
// @param key AES128-->16 , AES192-->24 , AES256-->32
// @return []byte
// @return error
//
func aesEncrypt(origData []byte, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	origData = PKCS7Padding(origData, blockSize)
	blocMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	encrypted := make([]byte, len(origData))
	blocMode.CryptBlocks(encrypted, origData)
	return encrypted, nil
}

//
// aesDecrypt
// @Description:
// @param encrypted
// @param key AES128-->16 , AES192-->24 , AES256-->32
// @return []byte
// @return error
//
func aesDecrypt(encrypted []byte, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
	origData := make([]byte, len(encrypted))
	blockMode.CryptBlocks(origData, encrypted)
	origData, err = PKCS7UnPadding(origData)
	if err != nil {
		return nil, err
	}
	return origData, err
}

//
// EncodeAESBase64
// @Description:
// @param pwd
// @return string
// @return error
//
func EncodeAESBase64(data []byte) (string, error) {
	if result, err := aesEncrypt(data, key); err != nil {
		return "", err
	} else {
		return base64.StdEncoding.EncodeToString(result), err
	}
}

//
// DecodeAESBase64
// @Description:
// @param pwd
// @return []byte
// @return error
//
func DecodeAESBase64(data string) ([]byte, error) {
	if pwdByte, err := base64.StdEncoding.DecodeString(data); err != nil {
		return nil, err
	} else {
		return aesDecrypt(pwdByte, key)
	}
}
